function TreeNode(val) {
    this.val = val;
    this.left = null;
    this.right = null;
}

// let root = new TreeNode('A');

function preorder(node) {
    let out = []
    if (!node) return;
    console.log(node.val);
    preorder(node.left);
    preorder(node.right);
    return out;
}


function midorder(node) {
    let out = [];
    if (!node) return;
    midorder(node.left);
    console.log(node.val);
    midorder(node.right);
    return out;
}

function levelOrder(root) {
    const result = [];

    function traverse(node, level) {
        if (!node) return;

        // 如果当前层级的结果数组还不存在，创建一个
        if (!result[level]) {
            result[level] = [];
        }

        // 将节点值存入对应层级
        result[level].push(node.val);

        // 递归遍历左右子树，层级+1
        traverse(node.left, level + 1);
        traverse(node.right, level + 1);
    }

    traverse(root, 0);
    return result;
}



// 构建示例二叉树
const root = new TreeNode(3);
root.left = new TreeNode(9);
root.right = new TreeNode(20);
root.right.left = new TreeNode(15);
root.right.right = new TreeNode(7);
//        3
//      9   20
//        15   7
//

// 执行层序遍历
console.log(levelOrder(root));
// 输出: [[3], [9, 20], [15, 7]]